package com.Pan;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.Pan.mapper.Base64RidMapper;
import com.Pan.mapper.PecUrlMapper;
import com.Pan.pojo.Base64Rid;
import com.Pan.pojo.PecUrl;
import com.Pan.pojo.SubmitGroup;
import com.Pan.pojo.SubmitImage;
import com.Pan.pojo.SubmitReq;
import com.Pan.util.HttpConnectionUtils;
import com.Pan.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import sun.rmi.runtime.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author lipanJia
 * @date 2021-11-29 14:35
 */
@SpringBootTest
@Slf4j
public class ResponseSubmit {

    // 腾讯云环境url提交：
    private final static String TX_URL_SUBMIT = "http://mobileout.langjtech.com/business/api/trax/imgRecog/urlSubmit";

    // 标准环境url提交：
    private final static String BZ_URL_SUBMIT = "https://mobile.lenztechretail.com/business/api/trax/imgRecog/urlSubmit";

    // 标准环境base64提交
    private final static String BZ_BASE_64_SUBMIT = "https://mobile.lenztechretail.com/business/api/trax/imgRecog/base64submit";

    // UAT环境url提交
    private final static String UAT_URL_SUBMIT = "https://perfeitti-uat.langjtech.com/business/api/trax/imgRecog/urlSubmit";

    // UAT环境BASE64提交
    private final static String UAT_BASE64_SUBMIT = "https://perfeitti-uat.langjtech.com/business/api/trax/imgRecog/base64submit";

    // 腾讯环境base64提交
    private final static String TX_BASE_64_SUBMIT = "http://mobileout.langjtech.com/business/api/trax/imgRecog/base64submit";

    // 新测试 URL提交
    private final static String NEW_TEST_SUBMIT = "https://mobile-test.langjtech.com/business/api/trax/pec/imgRecog/urlSubmit";

    // 新测试 base64提交
    private final static String NEW_TEST_BASE64_SUBMIT = "https://mobile-test.langjtech.com/business/api/trax/pec/imgRecog/base64submit";

    @Autowired
    private Base64RidMapper base64RidMapper;

    @Autowired
    private PecUrlMapper pecUrlMapper;

    /**
     * 通过base64提交单张图片
     * 注意观察文件夹图片数量变化，提交成功后会删除提交成功图片
     * 保存rid数据库名为 "base64_rid"
     * 自动插入数据库
     *
     * @throws JSONException
     * @throws InterruptedException
     */
    @Test
    void contextLoadBase() throws InterruptedException {
        // 替换图片路径
        File file = new File("E:\\传图文件夹\\江中测试 - 副本");
        // 输入问卷的taskId
        String taskId = "dbe36bad77964849a6c1775ea23c4bac";
        // 输入问卷的Qid
        String qId = "50af85223dd443448610026fdc3525f7";

        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            Base64Rid base64Rid = new Base64Rid();
            File file1 = files[i];
            String IdImage64Str = convertFileToBase64(file1);
            String imageName = file1.getName();
            System.out.println(IdImage64Str);
            List<String> strings = Arrays.asList("1", UUID.randomUUID().toString());
            String json = "{\n" +
                    "    \"businessDataParamList\": [\n" +
                    "        \"" + "AutoTest_" + strings + "\"  \n" +
                    "    ],\n" +
                    "    \"companyId\": \"1000049\",\n" +
                    "    \"pictureGroupList\": [\n" +
                    "        {\n" +
                    "            \"groupId\": \"0\",\n" +
                    "            \"groupPictureList\": [\n" +
                    "                {\n" +
                    "                    \"columnNo\": 1,\n" +
                    "                    \"id\": \"111\",\n" +
                    "                    \"picName\": \"" + imageName + "\",\n" +
                    "                    \"base64Code\": \"" + IdImage64Str + "\",\n" +
                    "                    \"rowNo\": 1\n" +
                    "                }\n" +
                    "            ],\n" +
                    "            \"qId\": \"" + qId + "\"\n" +
                    "        }\n" +
                    "    ],\n" +
                    "    \"taskId\": \"" + taskId + "\",\n" +
                    "    \"test\": 1\n" +
                    "}";
            System.out.println(json);
            try {
                String str = HttpConnectionUtils.post(NEW_TEST_BASE64_SUBMIT, json);
                System.out.println(str);
                JSONObject jsonObject = JSONObject.parseObject(str);
                String responseId = (String) jsonObject.getJSONObject("retData").get("responseId");
                base64Rid.setResponseId(responseId);
                base64RidMapper.insert(base64Rid);
                System.out.println("第" + file1 + "个已提交");
                // 删除指定位置的本地图片(删除成功返回true,失败返回false)
                System.out.println("提交图片是否已删除: " + file1.delete());
            } catch (Exception e) {
                log.error("提交失败, 即将重试!");
                contextLoadBase();
            }
            Thread.sleep(2000);
        }
    }


    /**
     * 通过url提交单张图片
     *
     * @throws JSONException
     * @throws InterruptedException
     */
    @Test
    void UrlSubmit() throws JSONException, InterruptedException {

        String taskId = "20220303130856287209732417130496";
        String qId = "20220303134252287218274482130944";

        List<PecUrl> pecUrls = pecUrlMapper.getNewResponseIdNull();
        for (PecUrl pecUrl : pecUrls) {
            String imageUrl = pecUrl.getImgUrl();
            List<String> strings = Arrays.asList("1", UUID.randomUUID().toString());
            String json = "{\n" +
                    "    \"businessDataParamList\": [\n" +
                    "        \"AutoTest_" + strings + "\"  \n" +
                    "    ],\n" +
                    "    \"companyId\": \"1000020\",\n" +
                    "    \"pictureGroupList\": [\n" +
                    "        {\n" +
                    "            \"groupId\": \"0\",\n" +
                    "            \"groupPictureList\": [\n" +
                    "                {\n" +
                    "                    \"columnNo\": 1,\n" +
                    "                    \"id\": \"111\",\n" +
                    "                    \"picName\": \"11.jpg\",\n" +
                    "                    \"rowNo\": 1,\n" +
                    "                    \"url\": \"" + imageUrl + "\"\n" +
                    "                }\n" +
                    "            ],\n" +
                    "            \"qId\": \"" + qId + "\"\n" +
                    "        }\n" +
                    "    ],\n" +
                    "    \"taskId\": \"" + taskId + "\",\n" +
                    "    \"test\": 1\n" +
                    "}";
            System.out.println(json);
            try {
                String str = HttpConnectionUtils.post(TX_URL_SUBMIT, json);
                String responseId = (String) JSONObject.parseObject(str).getJSONObject("retData").get("responseId");
                /*PecUrl pecUrl1 = new PecUrl();
                pecUrl1.setId(pecUrl.getId());
                pecUrlMapper.updateById(pecUrl1);*/
                Thread.sleep(5000);
            } catch (Exception e) {
                UrlSubmit();
            }
        }
    }

    /**
     * 通过url提交多张图片
     *
     * @throws JSONException
     * @throws InterruptedException
     */
    @Test
    void moreUrlSubmit() throws JSONException, InterruptedException {

        String taskId = "6208e60b7df345afb4c1ba0c1409900a";
        String qId = "66ae72638222480abe615d97608a8c93";
        int i = 1;

        while (true) {
            Page<PecUrl> pecUrlPage = new Page<>(1, 5);
            IPage<PecUrl> pecUrlIPage = pecUrlMapper.selectPage(pecUrlPage, null);
            if (pecUrlIPage.getRecords().size() == 0) {
                return;
            }
            List<String> imgUrlList = pecUrlIPage.getRecords().stream().map(PecUrl::getImgUrl).collect(Collectors.toList());
            String json = getJson(imgUrlList, taskId, qId);
            System.out.println(json);
            String str = HttpConnectionUtils.post(UAT_URL_SUBMIT, json);
            String responseId = (String) JSONObject.parseObject(str).getJSONObject("retData").get("responseId");
            Base64Rid base64Rid = new Base64Rid();
            base64Rid.setResponseId(responseId);
            base64Rid.setId(++i);
            base64RidMapper.insert(base64Rid);
            List<Integer> id = pecUrlIPage.getRecords().stream().map(PecUrl::getId).collect(Collectors.toList());
            LambdaQueryWrapper<PecUrl> idWrapper = new LambdaQueryWrapper<>();
            idWrapper.in(PecUrl::getId, id);
            pecUrlMapper.delete(idWrapper);
            Thread.sleep(1000);
        }

    }


    /**
     * 本地图片转base64码
     *
     * @param file
     * @return
     */
    public String convertFileToBase64(File file) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        String base64Str = Base64.getEncoder().encodeToString(data);

        return base64Str;
    }

    private String getJson(List<String> testTempList, String taskId, String qId) {
        // 接收batchId，和关于本条batchId相同的几份答卷。
        // 首先处理每一个答卷最里层图片集合
        // 创建一个最里层图片list集合对象
        List<SubmitImage> imageList = new ArrayList<>();
        int i = 1;
        // 遍历传进来的几份答卷，重复直到传进来的答卷遍历完成
        for (String imgUrl : testTempList) {
            // 创建一个图片集合对象
            SubmitImage submitImage = new SubmitImage();
            // 取出url，set进去，set每一个参数的值
            submitImage.setUrl(imgUrl);
            submitImage.setId(String.valueOf(i++));
            submitImage.setColumnNo(i);
            submitImage.setRowNo(1);
            // 把set进去的值存入list数组，
            imageList.add(submitImage);
        }

        // 处理第二层图片组，创建图片组list集合
        List<SubmitGroup> pictureGroupList = new ArrayList<>();
        // 创建图片组对象，set数据
        SubmitGroup group = new SubmitGroup();
        group.setGroupId("01");
        group.setqId(qId);
        // 这里传入上一步保存好的list图片集合
        group.setGroupPictureList(imageList);
        // 把set进去的值存入创建的图片组list集合
        pictureGroupList.add(group);

        // 处理最外层请求对象,创建最外层对象，set值
        SubmitReq req = new SubmitReq();
        req.setCompanyId("trax");
        req.setBusinessDataParamList(Arrays.asList("1", UUID.randomUUID().toString()));
        req.setTaskId(taskId);
        // 这里传入上一步保存好的图片组list集合
        req.setPictureGroupList(pictureGroupList);
        // 返回拼接好的json信息
        return JsonUtil.toJsonString(req);
    }

}


